package com.tvunetworks.device.extra.service.impl;

import com.tvunetworks.center.common.exception.ServerException;
import com.tvunetworks.center.common.model.LoginUser;
import com.tvunetworks.center.common.model.User;
import com.tvunetworks.center.common.util.Result;
import com.tvunetworks.device.extra.constants.ResultConstant;
import com.tvunetworks.device.extra.service.UserService;
import com.tvunetworks.device.extra.service.feign.UserFeignService;
import com.tvunetworks.device.extra.service.feign.UserGroupFeignService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * @author Etan Yang
 * @create: 2021/11/19 16:49
 */

@Service
@Slf4j
public class UserServiceImpl implements UserService {
    @Autowired
    private UserFeignService userFeignService;
    @Autowired
    private UserGroupFeignService userGroupFeignService;


    @Override
    public LoginUser getLoginUserByUserIdFromCcUserService(String userId) {
        try {
            return userFeignService.getLoginUserByUserId(userId);
        } catch (Exception e) {
            log.error("getLoginUserByUserIdFromCcUserService>>>>>>>getLoginUserFromCcServiceException,userId:[{}]", userId, e);
            throw new ServerException(ResultConstant.User.CALL_CC_USER_SERVICE_EXCEPTION);
        }
    }

    @Override
    public User getUserByUserIdFromUserGroup(String userId, boolean existFlag) {
        try {
            Result<User> userResult = userGroupFeignService.getUserInfoById(userId);
            if (!userResult.assertSuccess()) {
                log.error("getUserByUserIdFromUserGroup>>>>>>>userResult is not success, userId:[{}], userResult:[{}]", userId, userResult);
                throw new ServerException(ResultConstant.User.CALL_USER_GROUP_SERVICE_EXCEPTION.setErrorInfo(userResult.getErrorInfo()));
            }
            User user = userResult.getResult();
            if (existFlag && user == null) {
                log.error("getUserByUserIdFromUserGroup>>>>>user not exist,userId:[{}],userResult:[{}]", userId, userResult);
                throw new ServerException(ResultConstant.User.USER_NOT_EXIST);
            }
            return user;
        } catch (Exception e) {
            log.error("getUserByUserIdFromUserGroup>>>>>>>exception,userId:[{}],e:[{}]", userId, e);
            throw new ServerException(ResultConstant.User.CALL_USER_GROUP_SERVICE_EXCEPTION);
        }
    }

    @Override
    public void createLoginUserByUserIdAndEmail(String userId, String email) {
        try {
            userFeignService.createUserInCcService(userId, email);
        } catch (Exception e) {
            log.error("createLoginUserByUser>>>>>>>createLoginUserByUserException,userId:[{}],email:[{}]", userId, email, e);
            throw new ServerException(ResultConstant.User.CALL_CC_USER_SERVICE_EXCEPTION);
        }
    }
}
